<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script>
  const target = {
    name: 'jack',
    age: 18,
    friend: {
      name: 'Tom',
    }
  }

  function deepClone(target, map = new Map()) {
    //如果不是数组或对象 直接返回值
    if (typeof target !== 'object' || target === null) {
      return target
    }
    //判断要拷贝的是对象还是数组
    let result = Array.isArray(target) ? [] : {}
    //如果有拷贝过这个对象 直接返回
    if (map.get(target)) {
      return map.get(target);
    }
    //存储对应关系
    map.set(target, result)
    //递归
    for (let key in target) {
      //对象原型上的属性不用拷贝 只考虑自身的属性
      if (target.hasOwnProperty(key))
        result[key] = deepClone(target[key], map)
    }
    return result
  }

  //  function deepClone(target, map = new Map()) {
  //  if (typeof target === 'object') {
  //    let cloneTarget = Array.isArray(target) ? [] : {};
  //    console.log(cloneTarget)
  //    if (map.get(target)) {
  //      return map.get(target);
  //    }
  //    map.set(target, cloneTarget);
  //    console.log(map)
  //    for (const key in target) {
  //      cloneTarget[key] = deepClone(target[key], map);
  //    }
  //    return cloneTarget;
  //  } else {
  //    return target;
  //  }
  //};

  const newTarget = deepClone(target)
  //这个方法依然可以实现
  //const newTarget = JSON.parse(JSON.stringify(target))
  //测试
  //newTarget.friend.name = '小明'
  //newTarget.age = 99
  //console.log(target)
  //console.log(newTarget)

</script>
</body>
</html>
